package top.moxingwang.javawork.concurrent;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreTest {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 8; i++) {
            new Thread(() -> {
                try {
                    System.out.println( Thread.currentThread().getName()+ " 开始抢车位");
                    semaphore.acquire();
                    System.out.println( Thread.currentThread().getName()+ " 抢到车位");

                    TimeUnit.SECONDS.sleep(new Random().nextInt(10));


                    semaphore.release();
                    System.out.println(Thread.currentThread().getName()+ " 释放车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }
    }
}
